package com.guiji.quartz.domain;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.task.DataSaveUtil;
import com.guiji.quartz.util.DelPicUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description: 需要代理
 * @author: wangxw
 * @date 2021/11/24 11:13
 */
public class Timesofindia {
	private static final Logger log = LoggerFactory.getLogger(Timesofindia.class);

	public static void mainMethod() throws Exception {
		List<String> list = new ArrayList<>();
		list.add("https://timesofindia.indiatimes.com/business/cryptocurrency");
		list.add("https://timesofindia.indiatimes.com/business/stock-market");
		list.add("https://timesofindia.indiatimes.com/gadgets-news");
		list.forEach(url ->{
			HttpResponse response = null;
			try {
				response = HttpRequest.get(url)
					.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
					.header("Accept-Encoding", "gzip, deflate")
					.setHttpProxy(ProxyConfig.url, ProxyConfig.ip)
					.setConnectionTimeout(30000)
					.execute();

				if (null != response) {
					String category = "Timesofindia-Cryptocurrency";
					if(url.contains("stock")){
						category = "timesofindia-Market";
					}
					if(url.contains("gadgets")){
						category = "timesofindia-GadgetsForMen";
					}

					if (response.getStatus() == 200) {
						List<HttpCookie> cookies = response.getCookies();
						String resp = response.body();
						Set<String> resUrl = getUrl(resp,category);
						getContent(resUrl, cookies,category);
					} else {
						log.error("https://timesofindia.indiatimes.com/business/cryptocurrency " + String.valueOf(response.getStatus()));
					}
				} else {
					log.error("https://timesofindia.indiatimes.com/business/cryptocurrency " + String.valueOf(response.getStatus()));
				}

			} catch (Exception e) {
				log.error("访问 https://timesofindia.indiatimes.com/business/cryptocurrency 失败" + e);
				return;
			}
		});

	}

	private static void getContent(Set<String> listContent, List<HttpCookie> cookies,String category) throws MalformedURLException, URISyntaxException, InterruptedException {
		for (String url : listContent) {
			Thread.sleep(1000);
			if (!url.startsWith("https")) {
				url = new StringBuffer("https://timesofindia.indiatimes.com").append(url).toString();
			}

			if (null != cookies && cookies.size() > 0) {
				CookieManager ccm = new CookieManager();
				CookieStore CookieStore = ccm.getCookieStore();
				for (HttpCookie cookie : cookies) {
					URL domain = new URL("https://timesofindia.indiatimes.com/");
					CookieStore.add(domain.toURI(), cookie);
				}
				HttpRequest.setCookieManager(ccm);
			}

			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc;
			JXDocument jxDocument;
			try {
				HttpResponse response = HttpRequest.get(url).setHttpProxy(ProxyConfig.url, ProxyConfig.ip).setConnectionTimeout(15000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (Exception e) {
				log.info("代理失败2" + e);
				continue;
			}
			String title = null;
			try {
				title = (String) jxDocument.sel("//h1//text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			StringBuffer content = new StringBuffer();
			String contentStr = null;
			JXDocument jxDocumentP;
			Document document = null;
			String temp= null;
			try {

				document = Jsoup.parse(doc);
				String mainClass = "_3YYSt clearfix  ";
				if(category.equals("timesofindia-GadgetsForMen")) {
					mainClass = "ga-headlines";
				}
				Element mainArea = document.getElementsByClass(mainClass).get(0);
				contentStr = mainArea.toString();
				temp= contentStr.replaceAll("\n","").replaceAll("<br>", "\\$\\$\\$")+"$$$";

				jxDocumentP = new JXDocument(temp);
				contentStr = jxDocumentP.sel("//text()").get(0).toString();

			} catch (Exception e) {
				continue;
			}

			List<Object> srcImgs = new ArrayList<>();
			List<String> newImgs = new ArrayList<>();
			String img = null;
			try {
				String imgXpath  ="//div[@class='_3gupn']//img/@src";
				if(category.equals("timesofindia-GadgetsForMen")) {
					imgXpath = "//div[@class='_3v5m2 image_wrapper ']//img/@src";
				}
				int imgSize = jxDocument.sel(imgXpath).size();
				if (imgSize > 0) {
					for (int k = 0; k < imgSize; k++) {
						temp = jxDocument.sel(imgXpath).get(k).toString();
						img = temp.strip();
						srcImgs.add(img);
					}
				}

			} catch (Exception e) {
				log.error("可能没有图片");
				img = "";
			} finally {
				if (srcImgs.size() > 0) {
					newImgs = DelPicUtil.delPic(srcImgs);
				}
			}

			Date date = new Date();
			if (contentStr.length() > 50000 || contentStr.replaceAll("\\$|[\\s\\p{Zs}]", "").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				System.out.println("=======================================================");
				System.out.println(url);
				System.out.println(title);

				for (Object imgitem : srcImgs) {
					System.out.println(" " + imgitem);
				}
				System.out.println(contentStr);
				System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
				DataSaveUtil.saveData(title, contentStr, newImgs, url, date, "https://timesofindia.indiatimes.com/business/cryptocurrency", category);
				log.info(Thread.currentThread().getName() + "-----------------{}----------------",category);
			} catch (Exception e) {
				continue;
			}

		}
	}

	private static Set<String> getUrl(String content,String category) {

		Set<String> res = new HashSet<>();
		String pattern = "https://timesofindia.indiatimes.com/business/(cryptocurrency)?(india-business)?/.*?.cms";
		if(category.equals("timesofindia-GadgetsForMen")){
			pattern = "https://timesofindia.indiatimes.com/gadgets-news/.*?.cms";
		}
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			String temp = m.group();
			res.add(temp);
		}
		return res;
	}


//	public static void main(String[] args) throws Exception {
//		mainMethod();
//	}

}




